package com.softtek.ibeacon.service;

import java.io.Serializable;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.softtek.ibeacon.common.ReflectionUtils;
import com.softtek.ibeacon.dao.DAO;

public class BaseServiceImpl implements BaseService {

	@Autowired
	@Qualifier("baseDAO")
	protected DAO dao;

	private static Logger logger = LoggerFactory
			.getLogger(BaseServiceImpl.class);

	public DAO getDAO() {
		return dao;
	}

	@Override
	public Object save(Object entity) throws Exception {
		Object pk = getDAO().save(entity);
		String id = getDAO().getPk(entity.getClass()).keySet().toArray()[0]
				+ "";
		String type = ReflectionUtils.getAccessibleField(entity, id).getType()
				.getName();
		if ("java.lang.Integer".equals(type) || "int".equals(type)) {
			pk = Integer.parseInt(pk.toString());
		} else if ("java.lang.Long".equals(type) || "long".equals(type)) {
			pk = Long.parseLong(pk.toString());
		}
		ReflectionUtils.setFieldValue(entity, id, pk);
		return entity;
	}

	@Override
	public int delete(Object entity) throws Exception {
		return getDAO().delete(entity);
	}

	@Override
	public Map<String, Object> findById(Class<?> entityClass, Serializable id) {
		return getDAO().findById2Map(entityClass, id);
	}

}
